import {Tag} from '@models/Tag.ts';
import {ResourceExtensionInformation} from "@models//ResourceExtensionInformation.ts";

export class Resources {
    rId: number
    rName: string
    rManufacturer: string
    rType: string
    rJpeg: string
    rEnterTime: Date
    upUser: number
    rIntroduction: string

    tags: Tag[]
    rPicture: string[]
    resourceExtensionInformation: ResourceExtensionInformation

    constructor() {
        this.rId = 0
        this.rName = ''
        this.rManufacturer = ''
        this.rType = ''
        this.rJpeg = ''
        this.rEnterTime = new Date()
        this.upUser = 0
        this.rIntroduction = ''
        this.tags = []
        this.rPicture = []
        this.resourceExtensionInformation = {
            linkPrice: -1,
            downloadLocallyPrice: -1,
            hasDownloadLocally: '',
            rId: -1
        }
    }

    static fromApiResponse(data: any): Resources {
        const r = new Resources()

        r.rId = data.rId
        r.rName = data.rName ?? ''
        r.rManufacturer = data.rManufacturer ?? ''
        r.rType = data.rType ?? ''
        r.rJpeg = data.rJpeg ?? ''
        r.rEnterTime = data.rEnterTime ? new Date(data.rEnterTime) : new Date('1970-01-01')
        r.upUser = data.upUser ?? 0
        r.rIntroduction = data.rIntroduction ?? ''

        // 解析 tags 列表
        if (Array.isArray(data.tags)) {
            r.tags = data.tags.map((t: any) => Tag.fromTag(t))
        }

        // 解析图片列表
        if (Array.isArray(data.rPicture)) {
            r.rPicture = data.rPicture
        }

        // 解析嵌套对象
        if (data.resourceExtensionInformation) {
            r.resourceExtensionInformation = ResourceExtensionInformation.fromResourceExtensionInformation(data.resourceExtensionInformation)
        }

        return r
    }
}